package ren.nearby.home;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import ren.nearby.bean.beans.ARouterBean;
import ren.nearby.bean.beans.LoginBean;
import ren.nearby.bean.beans.VersionBean;
import ren.nearby.home.aop.HomeAspect;
import ren.nearby.home.mvp.FragmentActAction;
import ren.nearby.home.mvp.FragmentContract;
import ren.nearby.lib.http.ARouterConstants;
import ren.nearby.lib.http.meepo.Meepo;
import ren.nearby.lib.http.meepo.config.UriConfig;
import ren.nearby.lib.http.permission.Permission;
import ren.nearby.lib.http.permission.RxPermissions;
import ren.nearby.lib.ui.base.BaseActivity;
import ren.nearby.lib.ui.base.BaseLazyLoadFragment;
import ren.nearby.lib.ui.base.IPresenter;
import ren.nearby.lib.ui.permission.PermissionBean;
import ren.nearby.lib.ui.permission.PermissionBuild;
import ren.nearby.lib.ui.permission.PermissionDialogFragment;
import ren.nearby.lib.ui.view.PublicDialog;
import ren.nearby.lib.utils.ToastUtils;


/**
 * Created by Administrator on 2017/7/27 0027.
 */

public class NearbyFragmentMe extends BaseLazyLoadFragment implements FragmentContract.View, PermissionDialogFragment.OnCancelClick {

    ActivityRouter router;

    //    @BindView(R2.id.home_tv_test_platform)
    TextView home_tv_platform;
    //    @BindView(R2.id.home_tv_home)
    TextView home_tv_home;
    //    @BindView(R2.id.home_tv_main)
    TextView home_tv_main_login;
    TextView home_tv_fragment;
    //    @BindView(R2.id.home_tv_view)
    TextView home_tv_view_web;
    TextView home_tv_main_web;
    TextView home_tv_main_code;

    //    @BindView(R2.id.home_tv_test_view)
    TextView home_tv_view_welcome;
    TextView home_tv_test_view_login;
    TextView home_tv_jni_bitap;
    TextView home_tv_dagger2_template;
    TextView home_tv_tinker;

    //    @BindView(R2.id.home_tv_test_browsable)
    TextView home_tv_browser;
    TextView home_tv_permissions;
    TextView home_tv_jni_bitmap;
    TextView home_tv_launcher_icon;


    RxPermissions rxPermissions;

    @Override
    public void showUpload(VersionBean bean) {

    }

    @Override
    public void setProgress(long contentLength, long progress, long total) {

    }

    @Override
    public void startUi() {

    }

    @Override
    public void installationApk(File file) {

    }

    public void doublePermissions() {

    }

    @Override
    public void setPresenter(FragmentActAction presenter) {

    }


    private PublicDialog.Builder dialog;


    public void singlePermissions() {
        rxPermissions.ensureEach(
                Manifest.permission.CALL_PHONE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .apply(new Observable<Object>() {
                    @Override
                    protected void subscribeActual(final Observer<? super Object> observer) {
                        Logger.e("subscribeActual = ");
                        observer.onNext(observer);
                        observer.onComplete();
               /* dialog = new PublicDialog.Builder(getActivity())
                        .setbody("我是内容帅气的小脸蛋")
                        .setTextTitle("我是标题栏")
                        .setPositiveButtonText("确认")
                        .setPositiveTextColor(R.color.red)
                        .setOnPositiveClicked(new PublicDialog.OnPositiveClicked() {
                            @Override
                            public void OnClick(View view, Dialog dialog) {
                                Logger.e("确认");
                                observer.onNext(observer);
                            }
                        })
                        .setNegativeButtonText("取消")
                        .setNegativeTextColor(R.color.white)
                        .setOnNegativeClicked(new PublicDialog.OnNegativeClicked() {
                            @Override
                            public void OnClick(View view, Dialog dialog) {
                                Logger.e("取消");

                            }
                        }).setCancelable(false)
                        .build();
                dialog.show();*/


                    }
                }).subscribe(new Observer<Permission>() {
            @Override
            public void onSubscribe(Disposable d) {
                Logger.e("onSubscribe = " + d.isDisposed());
            }

            @Override
            public void onNext(Permission permission) {
                Logger.e("onNext = " + permission.granted);

                if (permission.granted) {
                    Logger.e("已经授权的权限" + permission.name);
                } else if (permission.shouldShowRequestPermissionRationale) {
                    //拒绝
                    Logger.e("已经拒绝的权限" + permission.name);
                } else {
                    //拒绝 不再询问
                    Logger.e("不再询问的权限" + permission.name);
                }

            }

            @Override
            public void onError(Throwable e) {
                Logger.e("onError = " + e.toString());
            }

            @Override
            public void onComplete() {
                Logger.e("onComplete = ");
                if (permissions != null) {
                    permissions.dismiss();
                }
            }
        });
    }

    @Inject
    FragmentContract.Action action;

    @Inject
    LoginBean loginBean;


    @HomeAspect("home 测试来了")
    public void test2() {
        Logger.e("Hello, I am CSDN_LQR 测试来了");
//        singlePermissions();
    }

    @Override
    protected void initView(View view) {
        toolBarBuilder
                .setTitle(getResources().getString(R.string.home_me))
                .setBackgroundColor(R.color.colorPrimary)
                .setTitleColor(R.color.white)
                .build();
        home_tv_platform = view.findViewById(R.id.home_tv_platform);
        home_tv_home = view.findViewById(R.id.home_tv_home);
        home_tv_main_login = view.findViewById(R.id.home_tv_main_login);
        home_tv_fragment = view.findViewById(R.id.home_tv_fragment);
        home_tv_view_welcome = view.findViewById(R.id.home_tv_view_welcome);
        home_tv_main_code = view.findViewById(R.id.home_tv_main_code);

        home_tv_view_web = view.findViewById(R.id.home_tv_view_web);
        home_tv_main_web = view.findViewById(R.id.home_tv_main_web);
        home_tv_test_view_login = view.findViewById(R.id.home_tv_test_view_login);
        home_tv_jni_bitmap = view.findViewById(R.id.home_tv_jni_bitmap);
        home_tv_dagger2_template = view.findViewById(R.id.home_tv_dagger2_template);
        home_tv_tinker = view.findViewById(R.id.home_tv_tinker);
        home_tv_browser = view.findViewById(R.id.home_tv_browser);
        home_tv_permissions = view.findViewById(R.id.home_tv_permissions);
        home_tv_launcher_icon = view.findViewById(R.id.home_tv_launcher_icon);

        rxPermissions = new RxPermissions(getActivity());


        final Meepo meepo = new Meepo.Builder()
                .config(new UriConfig().scheme("action").host("nearby.action"))
                .build();
        router = meepo.create(ActivityRouter.class);

        home_tv_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                test2();
//                router.gotoHome(getActivity(), "Me界面而来");


            }
        });

        home_tv_fragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("value1", "值1");
                map.put("value2", "值2");

//                router.gotoB(NWelcome.this, map);
                //多个参数传递与跳转Code与返回
                map.put("value3", "值3");
                router.gotoFragment(getActivity(), "Me界面而来");
            }
        });


        home_tv_main_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Map<String, String> map = new HashMap<String, String>();
//                map.put("value1", "值1");
//                map.put("value2", "值2");
//
////                router.gotoB(NWelcome.this, map);
//                //多个参数传递与跳转Code与返回
//                map.put("value3", "值3");
//                router.gotoMainLogin(getActivity(), map);
                ARouter.getInstance().build(ARouterConstants.MAIN_LOGIN).navigation();
            }
        });

        home_tv_main_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Map<String, String> map = new HashMap<String, String>();
//                map.put("value1", "值1");
//                map.put("value2", "值2");
//
////                router.gotoB(NWelcome.this, map);
//                //多个参数传递与跳转Code与返回
//                map.put("value3", "值3");
//                router.gotoMainLogin(getActivity(), map, 103);
                ARouterBean aRouterBean = new ARouterBean();
                aRouterBean.setName("haha");
                aRouterBean.setAge(102);
                ARouter.getInstance()
                        .build(ARouterConstants.MAIN_LOGIN)
                        .withString("name", "haha2")
                        .withSerializable("bean", aRouterBean)
                        .navigation();

            }
        });


        home_tv_view_welcome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("value1", "值1");
                map.put("value2", "值2");

//                router.gotoB(NWelcome.this, map);
                //多个参数传递与跳转Code与返回
                map.put("value3", "值3");
                router.gotoViewWelcome(getActivity(), map);
            }
        });

        home_tv_view_web.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("value1", "值1");
                map.put("value2", "值2");

//                router.gotoB(NWelcome.this, map);
                //多个参数传递与跳转Code与返回
                map.put("value3", "值3");
//                router.gotoTestView(getActivity(),map);
                router.gotoViewH5Web(getActivity(), map);


            }
        });

        home_tv_main_web.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("value1", "http://47.105.115.121:82");
                map.put("value2", "值2");

//                router.gotoB(NWelcome.this, map);
                //多个参数传递与跳转Code与返回
                map.put("value3", "值3");
//                router.gotoTestView(getActivity(),map);
                router.gotoMainX5H5Web(getActivity(), map);


            }
        });
        home_tv_test_view_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("value1", "值1");
                map.put("value2", "值2");

//                router.gotoB(NWelcome.this, map);
                //多个参数传递与跳转Code与返回
                map.put("value3", "值3");
                router.gotoTestViewLogin(getActivity(), map);
            }
        });

        home_tv_jni_bitmap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("value1", "值1");
                map.put("value2", "值2");

//                router.gotoB(NWelcome.this, map);
                //多个参数传递与跳转Code与返回
                map.put("value3", "值3");
                router.gotoMainCompress(getActivity(), map);


            }
        });
        home_tv_dagger2_template.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("value1", "值1");
                map.put("value2", "值2");

//                router.gotoB(NWelcome.this, map);
                //多个参数传递与跳转Code与返回
                map.put("value3", "值3");
                router.gotoMainDagger2Template(getActivity(), map);


            }
        });
        home_tv_tinker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("value1", "值1");
                map.put("value2", "值2");

//                router.gotoB(NWelcome.this, map);
                //多个参数传递与跳转Code与返回
                map.put("value3", "值3");
                router.gotoMainTinker(getActivity(), map);
            }
        });
        home_tv_platform.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("value1", "值1");
                map.put("value2", "值2");

//                router.gotoB(NWelcome.this, map);
                //多个参数传递与跳转Code与返回
                map.put("value3", "值3");
                router.gotoMainPlatform(getActivity(), map);
            }
        });

        home_tv_browser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("http://bk.nearby.ren/naerby.html");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.setData(uri);
                startActivity(intent);


            }
        });
        isPermission();
        home_tv_permissions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<PermissionBean> permissions = new ArrayList<>();
                permissions.add(new PermissionBean(Manifest.permission.ACCESS_FINE_LOCATION, R.mipmap.easy_location, "开启定位功能", "GPS定位开启，便于筛选城市车辆"));
                permissions.add(new PermissionBean(android.Manifest.permission.
                        WRITE_EXTERNAL_STORAGE, R.mipmap.easy_storage, "存储权限", "缓存图片，降低流量消耗"));
                permissions.add(new PermissionBean(android.Manifest.permission.
                        CAMERA, R.mipmap.easy_camera, "相机权限", "资料提交需要开启相机"));
                final PermissionBuild.Builder builder = new PermissionBuild.Builder((BaseActivity) getActivity());
                builder.
                        setRequest(permissions)
                        .setPermiCancel(new PermissionBuild.PermiCancel() {
                            @Override
                            public void perCancel() {
                                Logger.e("Cancel");
                            }
                        }).setPermiOk(new PermissionBuild.PermiOk() {
                    @Override
                    public void perOk() {
                        Logger.e("Ok");
                        singlePermissions();
                    }
                }).build();


//                if (request.size() > 0) {
//                    permissions =
//                            PermissionDialogFragment
//                                    .newInstance(request);
//                    FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
//                    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//                    permissions.setOnCancelClick(NearbyFragmentMe.this);
//                    permissions.show(transaction, "permissions");
//                } else {
//                    Light.success(home_tv_permissions, "哈哈哈", Light.LENGTH_SHORT).show();
//                }

            }
        });
        home_tv_launcher_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clickCount2 == 2) {
                    clickCount2 = 0;
                    setDefaultAlias();
                } else if (clickCount == 0) {
                    clickCount++;
                    clickCount2++;
                    setAlias1();
                } else if (clickCount == 1) {
                    clickCount--;
                    clickCount2++;
                    setAlias2();
                }
            }
        });

    }

    int clickCount = 0;
    int clickCount2 = 0;

    public void setDefaultAlias() {
        ToastUtils.showToast(getActivity(), "已切换到恢复默认图标,大概10秒后生效");
        PackageManager packageManager = getActivity().getPackageManager();
        packageManager.setComponentEnabledSetting(new ComponentName(getActivity(), "ren.nearby.home.DefaultAlias"), PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
        packageManager.setComponentEnabledSetting(new ComponentName(getActivity(), "ren.nearby.home.SplashAct1"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
        packageManager.setComponentEnabledSetting(new ComponentName(getActivity(), "ren.nearby.home.SplashAct2"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager
                .DONT_KILL_APP);
    }

    public void setAlias1() {
        ToastUtils.showToast(getActivity(), "已切换到Alias1图标,大概10秒后生效");
        PackageManager packageManager = getActivity().getPackageManager();
        packageManager.setComponentEnabledSetting(new ComponentName(getActivity(),
                        "ren.nearby.home.DefaultAlias"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
        packageManager.setComponentEnabledSetting(new ComponentName(getActivity(), "ren.nearby.home.SplashAct1"), PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
        packageManager.setComponentEnabledSetting(new ComponentName(getActivity(), "ren.nearby.home.SplashAct2"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager
                .DONT_KILL_APP);
    }

    public void setAlias2() {
        ToastUtils.showToast(getActivity(), "已切换到Alias2图标,大概10秒后生效");
        PackageManager packageManager = getActivity().getPackageManager();
        packageManager.setComponentEnabledSetting(new ComponentName(getActivity(), "ren.nearby.home.DefaultAlias"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);

        packageManager.setComponentEnabledSetting(new ComponentName(getActivity(), "ren.nearby.home.SplashAct1"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
        packageManager.setComponentEnabledSetting(new ComponentName(getActivity(), "ren.nearby.home.SplashAct2"), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager
                .DONT_KILL_APP);
    }

    @Override
    public void ok() {
        singlePermissions();
    }

    @Override
    public void cancel() {
        if (permissions != null) {
            permissions.dismiss();
        }

    }

    PermissionDialogFragment permissions;
    ArrayList<PermissionBean> request = new ArrayList<>();

    public void isPermission() {
        List<PermissionBean> permissions = new ArrayList<>();
        permissions.add(new PermissionBean(Manifest.permission.ACCESS_FINE_LOCATION, R.mipmap.easy_location, "开启定位功能", "GPS定位开启，便于筛选城市车辆"));
        permissions.add(new PermissionBean(android.Manifest.permission.
                WRITE_EXTERNAL_STORAGE, R.mipmap.easy_storage, "存储权限", "缓存图片，降低流量消耗"));
        permissions.add(new PermissionBean(android.Manifest.permission.
                CAMERA, R.mipmap.easy_camera, "相机权限", "资料提交需要开启相机"));
        permissions.add(new PermissionBean(android.Manifest.permission.
                KILL_BACKGROUND_PROCESSES, R.mipmap.easy_camera, "相机权限", "资料提交需要开启相机"));

        for (PermissionBean permission : permissions) {
            if (!rxPermissions.isGranted(permission.getName()) && !rxPermissions.isRevoked(permission.getName())) {
                request.add(permission);
            }
        }
    }

    @Override
    protected BaseLazyLoadFragment getFragment() {
        return this;
    }

    @Override
    public IPresenter getPresenter() {
        return null;
    }


    @Override
    public void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
    }

    @Override
    public void onFragmentResume() {
        super.onFragmentResume();
    }

    @Override
    public void onFragmentPause() {
        super.onFragmentPause();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.home_neraby_fragment_me;
    }

    /**
     * 测试router.gotoViewWelcome2 方法返回
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //测试Meepo请求code返回
        Logger.e(" me Home 组件 " + "requestCode = " + requestCode + " - resultCode = " + resultCode);


    }
}
